package problems;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import lib.Permutations;

public class Euler032 extends AbstractEuler {

	@Override
	public Number calculate() {
		List<String> digits = Arrays.asList("1", "2", "3", "4", "5", "6", "7", "8", "9");
		
		//List<List<Character>> permutations = new ArrayList<List<Character>>();
		Iterator<List<String>> p = new Permutations<String>(digits, digits.size());

		Set<Integer> answers = new HashSet<Integer>();
		
		//we can never get to more than 8 digits in total if there are 4 or less digits in the multiplier and multiplicand, because:
		//97 * 86 = 8342
		//9 * 876 = 7884
		
		//we can never get to less than 11 digits in total if there are 6 or more digits in the multiplier and multiplicand, because:
		//135 * 246 = 33210
		//13 * 2456 = 31928
		//1 * 23456 = 23456
		
		//therefore, there need to be 5 digits in the multiplier and multiplicand. There are two possible formats:
		//[1] * [4] = [4] and [2] * [3] = [4]. Switching the multiplier and multiplicand of course yields the same product.

		while (p.hasNext()) {
			List<String> perm = p.next();
			
			//try [2] * [3] = [4]
			Integer multiplier = 	Integer.valueOf(perm.get(0) + perm.get(1));
			Integer multiplicand =	Integer.valueOf(perm.get(2) + perm.get(3) + perm.get(4));
			Integer product = 		Integer.valueOf(perm.get(5) + perm.get(6) + perm.get(7) + perm.get(8));
			
			if (multiplier * multiplicand == product) {
//				System.out.println(multiplier + "*" + multiplicand + "=" + product);
				answers.add(product);
			}

			
			//try [1] * [4] = [4]
			multiplier = Integer.valueOf(perm.get(0));
			multiplicand =	Integer.valueOf(perm.get(1) + perm.get(2) + perm.get(3) + perm.get(4));

			if (multiplier * multiplicand == product) {
//				System.out.println(multiplier + "*" + multiplicand + "=" + product);
				answers.add(product);
			}
			
		}
		
		int sumOfProducts = 0;
		
//		System.out.println("products: " + answers);
		
		for (Object i : answers.toArray()) {
			sumOfProducts += (Integer)i;
		}
		return sumOfProducts;
	}


	@Override
	protected Number getCorrectAnswer() {
		return 45228;
	}

}
